package com.handtransaction.controller;

import com.google.gson.Gson;
import com.handtransaction.entity.User;
import com.handtransaction.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理用户端的控制器
 */

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 处理注销功能，即退出登录
     */
    @RequestMapping(value = "tologout",method = RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        request.getSession().invalidate();
//        HttpSession session = request.getSession();
//        session.removeAttribute("user");
//        response.sendRedirect(request.getContextPath());
        return "redirect:/ShowALLGoods";
    }

    /***
     * 切换账号
     */
    @RequestMapping(value = "gotologin",method = RequestMethod.GET)
    public ModelAndView gotologin(HttpServletRequest request, HttpServletResponse response,ModelAndView model)throws ServletException, IOException{
        model.setViewName("user/login");
        return model;
    }

    //  跳转到注册页面
    @RequestMapping(value = "toregister",method = RequestMethod.GET)
    public ModelAndView toregist(HttpServletRequest request,HttpServletResponse response,ModelAndView modelAndView)throws ServletException,IOException{
        modelAndView.setViewName("user/register");
        return modelAndView;
    }

    /**
     * 处理注册功能
     * @param request
     * @param response
     * @param user
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "regist",method = RequestMethod.POST)
    public String regist(HttpServletRequest request, HttpServletResponse response, User user,ModelAndView modelAndView){

            userService.registUser(new User(null, user.getUpassword(), user.getUname(), user.getUfaculty(),
                    user.getUphone(), 1, user.getUbalance(),user.getUnumber(),user.getUsign()));
            return "user/login";
    }

    /**
        使用ajax验证注册时用户名是否可用
     */

    @RequestMapping(value = "ajaxIsExistuname",method = RequestMethod.GET)
    public void ajaxIsExistuname(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String uname = request.getParameter("uname");
        boolean existsUname = userService.isExistsUsername(uname);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("existsUname",existsUname);
//创建Gson对象
        Gson gson = new Gson();
        String json = gson.toJson(map);
        response.getWriter().write(json);
    }

//    ajax验证学号是否存在
    @RequestMapping(value = "ajaxIsExistUnumber",method = RequestMethod.GET)
    public void ajaxIsExistUnumber(HttpServletRequest request,HttpServletResponse response)throws IOException{
        Long unumber = Long.parseLong(request.getParameter("unumber"));
        boolean existsUnumber = userService.QueryUserByUnumber(unumber);
        Map<String,Object> map = new HashMap<>();
        map.put("existsUnumber",existsUnumber);
        Gson gson = new Gson();
        String json = gson.toJson(map);
        response.getWriter().write(json);
    }

    /**
     * 先获取用户信息再修改用户信息
     */
    @RequestMapping(value = "getUserInfo",method = RequestMethod.GET)
    public String getUserInfo(Model model, @RequestParam(value = "uid",required = true)int uid
    ,HttpServletRequest request,HttpServletResponse response){
        User user = userService.QueryUserByuid(uid);
        model.addAttribute("user",user);
        request.getSession().setAttribute("uimg_path",user.getUimg_path());
        return "user/userInfo1";
    }

    /**
     * 处理用户更新自己的个人信息
     * @param model
     * @param user
     * @param file
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "updateUserInfo",method = RequestMethod.POST)
    public String updateUserInfo(Model model, User user,
                                 @RequestParam(value = "imgfile",required = false) MultipartFile file
    ,HttpServletRequest request,HttpServletResponse response){
        //保存到数据库的路径
        String sqlPath = null;
//        处理头像上传---------------------------------------
        try {
            String path = request.getServletContext().getRealPath("/imgs/userimg");
            String fileName = file.getOriginalFilename();
            if(fileName!=""){
                File f = new File(path,fileName);
                if(!f.exists()){
                    f.mkdirs();
                    System.out.println(f);
                }
                file.transferTo(f);
                //把图片的相对路径保存至数据库
                sqlPath = "imgs/userimg/"+fileName;
                user.setUimg_path(sqlPath);
                request.getSession().setAttribute("uimg_path",sqlPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        --------------------------------------------------------
        userService.UpdateUserInfo(user);
        userService.UpDGoodsUname(user);
        request.getSession().setAttribute("user",user);
        return "common/succ";
    }

    /**
     * 修改用户密码
     * @param model
     * @param uid
     * @return
     */
    @RequestMapping(value = "toUserSafe",method = RequestMethod.GET)
    public String gotousersafe(Model model, @RequestParam(value = "uid",required = true)int uid){
        User user = userService.QueryUserByuid(uid);
        model.addAttribute("user",user);
        return "user/userSafe";
    }

    @RequestMapping(value = "updateUserInfo2",method = RequestMethod.POST)
    public String updateUserInfo2(Model model,User user){
        userService.UpdateUserInfo2(user);
        return "common/succ";
    }
    /**
     * 处理充值
     */
    @RequestMapping(value = "gotochongzhi",method = RequestMethod.GET)
    public String gotochong(Model model
            , @RequestParam(value = "uid",required = true)int uid
            ,HttpServletRequest request){
        User user = userService.QueryUserByuid(uid);
         model.addAttribute("user",user);
         request.getSession().setAttribute("user",user);
        System.out.println("该用户现在余额为："+user.getUbalance());
        return "user/ubalance";
    }

    @RequestMapping(value = "updatebal",method = RequestMethod.POST)
    public String updatebal(User user,ModelAndView modelAndView,HttpServletRequest request,Model model){

        userService.updateBlance(user);
        modelAndView.addObject("user",user);
        return "common/succ";
    }
}
